package com.admin.controller.system;

import com.admin.common.enums.EnumIstatus;
import com.admin.common.enums.EnumResult;
import com.admin.common.enums.MemberLevelEnum;
import com.admin.common.shiro.ShiroUtils;
import com.admin.common.util.DateUtils;
import com.admin.common.util.YsCollectionUtil;
import com.admin.controller.base.BaseController;
import com.admin.domain.AdminDO;
import com.admin.req.user.MemberReq;
import com.admin.service.AdminService;
import com.admin.service.DeclareUserService;
import com.admin.service.RoleService;
import com.admin.vo.PageVO;
import com.admin.vo.ResultVO;
import com.admin.vo.SimpleResultVO;
import com.admin.vo.system.*;
import com.aliyuncs.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 申报用户接口
 * 
 * @author ZY
 * @date 2018/09/30
 */
@Api(description = "申报用户接口")
@RestController
@RequestMapping(value = "/declare/admin")
public class DeclareAdminController extends BaseController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DeclareUserService declareUserService;

    @ApiOperation(value = "申报用户管理")
    @RequiresPermissions("declareUser:list")
    @GetMapping(value = "/declareUserList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "villageName", value = "社区名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "regionIds", value = "地区，号分割", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "开始时间", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "realname", value = "用户名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "用户状态", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "currentRoundDeclare", value = "本轮是否申报 0 否 1 是", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "currentRoundDeclareStatus", value = "本轮申报结果 0 未处理  1 通过 2 未通过", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "currentRoundDeclareSwitch", value = "申报开关 0 关  1 开", dataType = "int", paramType = "query"),
    })
    public ResultVO<PageVO<ListAdminVO>> declareUserList(Integer pageIndex, Integer pageSize, String villageName, String regionIds,
                                                         Integer createTime, Integer endTime, String realname, Integer status,
                                                         Integer currentRoundDeclare, Integer currentRoundDeclareStatus,Integer currentRoundDeclareSwitch) {
        Map<String, Object> params = YsCollectionUtil.createHashMap();
        params.put("villageName", villageName);
        if (!StringUtils.isEmpty(regionIds)) {
            List<Integer> searchRegionIds = new ArrayList<>();
            String[] regionIdArray  = regionIds.split(",");
            searchRegionIds.add(Integer.valueOf(regionIdArray[regionIdArray.length - 1]));
            params.put("searchRegionIds", searchRegionIds);
        }

        if (null != createTime && createTime != 0) {
            params.put("startTime", DateUtils.dateFormatStr(createTime));
        }
        if (null != endTime && endTime != 0) {
            params.put("endTime", DateUtils.dateFormatStr(endTime));
        }
        params.put("username", realname);
        params.put("istatus", status);
        params.put("role", 1);
        params.put("orderBy", "user_id");
        params.put("currentRoundDeclare", currentRoundDeclare);
        params.put("currentRoundDeclareStatus", currentRoundDeclareStatus);
        params.put("currentRoundDeclareSwitch", currentRoundDeclareSwitch);

        // 上级查看下级用户
        if (ShiroUtils.getMemberLevel().equals(MemberLevelEnum.AREA.getKey())) {
            params.put("areaIds", adminService.getResponsibleAreaIds());
        } else if (ShiroUtils.getMemberLevel().equals(MemberLevelEnum.CITY.getKey())) {
            params.put("cityIds", adminService.getResponsibleAreaIds());
        } else if (ShiroUtils.getMemberLevel().equals(MemberLevelEnum.PROVINCE.getKey())) {
            params.put("provinceIds", adminService.getResponsibleAreaIds());
        }
        return adminService.getPageList(pageIndex, pageSize, params);
    }


    @ApiOperation(value = "到新增用户页")
    @RequiresPermissions("declareUser:save")
    @GetMapping(value = "/toAdd")
    public ResultVO<AddAdminVO> toAddAdmin() {
        ResultVO<AddAdminVO> result = new ResultVO<>();
        AddAdminVO addAdminVO = new AddAdminVO();
        addAdminVO.setIstatusVOs(getIstatusSelectedVOs(EnumIstatus.OK.getKey()));
        addAdminVO.setRoleVOs(roleService.getSelectRoles().getData());
        result.setData(addAdminVO);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }


    @ApiOperation(value = "申报用户列表 -  新增申报用户")
    @RequiresPermissions("declareUser:save")
    @PostMapping(value = "/saveMember")
    public SimpleResultVO saveMember(@RequestBody MemberReq req) {
        return adminService.saveMember(req);
    }

    @ApiOperation(value = "到修改用户页")
    @RequiresPermissions("declareUser:update")
    @GetMapping(value = "/toUpdate")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "query")
    public ResultVO<UpdateAdminVO> toUpdateAdmin(Integer userId) {
        ResultVO<UpdateAdminVO> result = new ResultVO<>();
        UpdateAdminVO updateAdminVO = new UpdateAdminVO();
        AdminDO adminDO = adminService.selectByPrimaryKey(userId);
        BeanUtils.copyProperties(adminDO, updateAdminVO);
        updateAdminVO.setIstatusVOs(getIstatusSelectedVOs(adminDO.getIstatus()));
        updateAdminVO.setRoleVOs(roleService.getSelectRoles(userId).getData());
        result.setData(updateAdminVO);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }

    @ApiOperation(value = "申报用户列表 - 修改申报用户")
    @RequiresPermissions("declareUser:update")
    @PostMapping(value = "/updateMember")
    public SimpleResultVO updateMember(@RequestBody MemberReq req) {
        return adminService.updateMember(req);
    }


    @ApiOperation(value = "删除用户")
    @RequiresPermissions("declareUser:delete")
    @GetMapping(value = "/delete")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "query")
    public SimpleResultVO deleteAdmin(Integer userId) {
        SimpleResultVO result = new SimpleResultVO();
        declareUserService.delDeclareUser(userId);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }


    @ApiOperation(value = "检查是否有效登录")
    @GetMapping(value = "/checkValidLogin")
    public SimpleResultVO checkValidLogin() {
        return SimpleResultVO.ok();
    }

    /**
     * 筛选账号状态
     * 
     * @param istatusSelected
     * @return
     */
    private List<IstatusSelectedVO> getIstatusSelectedVOs(Integer istatusSelected) {
        List<IstatusSelectedVO> istatusVOs = new ArrayList<IstatusSelectedVO>();
        for (EnumIstatus e : EnumIstatus.values()) {
            IstatusSelectedVO istatusVO = new IstatusSelectedVO();
            istatusVO.setIstatus(e.getKey());
            istatusVO.setIstatusName(e.getText());
            if (e.getKey().equals(istatusSelected)) {
                istatusVO.setIsSelected(true);
            } else {
                istatusVO.setIsSelected(false);
            }
            istatusVOs.add(istatusVO);
        }
        return istatusVOs;
    }
}
